package com.cx.cglib;

import com.cx.common.utils.JsonUtils;
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author:cxy
 * @Date:2022/4/10 15:11
 */
public class CglibDynamicProxy implements MethodInterceptor {


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if(Object.class.equals(method.getDeclaringClass())){
            method.invoke(this,objects);
            return null;
        }
        System.out.println("开始");
        System.out.println(JsonUtils.object2String(objects));
        methodProxy.invokeSuper(o,objects);
        System.out.println("结束");
        return null;
    }


    public <T> Object getInstance(Class<T> type){
        System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"E:\\cxy");

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(type);
        enhancer.setCallback(this);
        return enhancer.create();
    }
}
